<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? $t('编辑提现记录') : $t('新增提现记录')"
    :mask-closable="false"
    width="650px"
    @cancel="close"
    @update:visible="(val: boolean) => emit('update:visible', val)"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-align="right"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item field="partnerId" :label="$t('运营商')" required>
        <a-select
          v-model="formData.partnerId"
          :placeholder="$t('请选择运营商')"
          allow-search
          :loading="partnerLoading"
          @change="handlePartnerChange"
        >
          <a-option
            v-for="option in partnerOptions"
            :key="option.id"
            :value="option.id"
            :label="option.partnerCode ? `${option.partnerCode} - ${option.partnerName}` : option.partnerName"
          >
            <span v-if="option.partnerCode" class="option-code">{{ option.partnerCode }}</span>
            <span class="option-name">{{ option.partnerName }}</span>
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="withdrawAmount" :label="$t('提现金额(元)')" required>
        <a-input-number
          v-model="formData.withdrawAmount"
          :placeholder="$t('请输入提现金额')"
          :min="0"
          :precision="2"
          :step="100"
          style="width: 100%"
          @change="calculateActualAmount"
        />
      </a-form-item>
      <a-form-item field="feeRate" :label="$t('手续费率(%)')">
        <a-input-number
          v-model="formData.feeRate"
          :placeholder="$t('请输入手续费率')"
          :min="0"
          :max="100"
          :precision="2"
          style="width: 100%"
          @change="calculateActualAmount"
        />
      </a-form-item>
      <a-form-item field="actualAmount" :label="$t('实际到账金额(元)')" required>
        <a-input-number
          v-model="formData.actualAmount"
          :placeholder="$t('请输入实际到账金额')"
          :min="0"
          :precision="2"
          style="width: 100%"
          disabled
        />
      </a-form-item>
      <a-form-item field="paymentMethod" :label="$t('打款方式')" required>
        <a-select
          v-model="formData.paymentMethod"
          :placeholder="$t('请选择打款方式')"
          allow-clear
          @change="handlePaymentMethodChange"
        >
          <a-option :value="PaymentMethod.BANK">{{ $t('银行转账') }}</a-option>
          <a-option :value="PaymentMethod.WECHAT">{{ $t('微信') }}</a-option>
          <a-option :value="PaymentMethod.ALIPAY">{{ $t('支付宝') }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="paymentName" :label="$t('收款人姓名')" required>
        <a-input
          v-model="formData.paymentName"
          :placeholder="$t('请输入收款人姓名')"
          allow-clear
        />
      </a-form-item>

      <!-- 银行转账信息 -->
      <template v-if="formData.paymentMethod === PaymentMethod.BANK">
        <a-form-item field="bankName" :label="$t('银行名称')" required>
          <a-input
            v-model="formData.bankName"
            :placeholder="$t('请输入银行名称')"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="bankAccount" :label="$t('银行账号')" required>
          <a-input
            v-model="formData.bankAccount"
            :placeholder="$t('请输入银行账号')"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="bankBranch" :label="$t('开户支行')">
          <a-input
            v-model="formData.bankBranch"
            :placeholder="$t('请输入开户支行')"
            allow-clear
          />
        </a-form-item>
      </template>

      <!-- 支付宝信息 -->
      <template v-if="formData.paymentMethod === PaymentMethod.ALIPAY">
        <a-form-item field="alipayAccount" :label="$t('支付宝账号')" required>
          <a-input
            v-model="formData.alipayAccount"
            :placeholder="$t('请输入支付宝账号')"
            allow-clear
          />
        </a-form-item>
      </template>

      <!-- 微信信息 -->
      <template v-if="formData.paymentMethod === PaymentMethod.WECHAT">
        <a-form-item field="wechatAccount" :label="$t('微信账号')" required>
          <a-input
            v-model="formData.wechatAccount"
            :placeholder="$t('请输入微信账号')"
            allow-clear
          />
        </a-form-item>
      </template>

      <a-form-item field="remark" :label="$t('备注')">
        <a-textarea
          v-model="formData.remark"
          :placeholder="$t('请输入备注信息')"
          allow-clear
        />
      </a-form-item>

      <!-- 打款凭证上传 -->
      <a-form-item field="paymentVoucher" :label="$t('打款凭证')" required>
        <a-upload
          :custom-request="handleUpload"
          :show-file-list="false"
          :limit="1"
          accept="image/*"
          :before-upload="beforeUpload"
          :auto-upload="true"
        >
          <template #upload-button>
            <a-button type="primary">
              <template #icon>
                <icon-upload />
              </template>
              {{ formData.paymentVoucher ? $t('重新上传') : $t('上传凭证') }}
            </a-button>
          </template>
        </a-upload>
        <div v-if="formData.paymentVoucher" class="preview-image">
          <img :src="formData.paymentVoucher" alt="打款凭证" />
        </div>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="close">{{ $t('取消') }}</a-button>
        <a-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ $t('确定') }}
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, watch } from 'vue';
import { FormInstance, Message } from '@arco-design/web-vue';
import axios from 'axios';
import { 
  PaymentMethod,
  PartnerWithdrawVO,
  createPartnerWithdraw,
  updatePartnerWithdraw
} from '@/api/partner/withdraw';
import { IconUpload } from '@arco-design/web-vue/es/icon';

// 运营商选项接口
interface PartnerOption {
  id: number;
  partnerName: string;
  partnerCode?: string;
  [key: string]: any;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object as PropType<PartnerWithdrawVO | null>,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'success']);

// 表单引用
const formRef = ref<FormInstance>();

// 提交状态
const submitting = ref(false);

// 运营商下拉选项
const partnerOptions = ref<PartnerOption[]>([]);
const partnerLoading = ref(false);

// 表单数据
const defaultFormData: PartnerWithdrawVO = {
  id: undefined,
  partnerId: undefined,
  partnerName: '',
  withdrawNo: '',
  withdrawAmount: undefined,
  feeRate: 0,
  actualAmount: undefined,
  paymentMethod: undefined,
  paymentName: '',
  bankName: '',
  bankAccount: '',
  bankBranch: '',
  alipayAccount: '',
  wechatAccount: '',
  remark: '',
  paymentVoucher: '',
  withdrawStatus: undefined,
  createTime: '',
  updateTime: ''
};

const formData = reactive<PartnerWithdrawVO>({ ...defaultFormData });

// 表单校验规则
const rules = {
  partnerId: [{ required: true, message: '请选择运营商' }],
  withdrawAmount: [{ required: true, message: '请输入提现金额' }],
  actualAmount: [{ required: true, message: '请输入实际到账金额' }],
  paymentMethod: [{ required: true, message: '请选择打款方式' }],
  paymentName: [{ required: true, message: '请输入收款人姓名' }],
  bankName: [{ 
    required: true, 
    message: '请输入银行名称',
    validator: (value: string, cb: (error?: string) => void) => {
      if (formData.paymentMethod === PaymentMethod.BANK && !value) {
        return cb('请输入银行名称');
      }
      cb();
    }
  }],
  bankAccount: [{ 
    required: true, 
    message: '请输入银行账号',
    validator: (value: string, cb: (error?: string) => void) => {
      if (formData.paymentMethod === PaymentMethod.BANK && !value) {
        return cb('请输入银行账号');
      }
      cb();
    }
  }],
  alipayAccount: [{ 
    required: true, 
    message: '请输入支付宝账号',
    validator: (value: string, cb: (error?: string) => void) => {
      if (formData.paymentMethod === PaymentMethod.ALIPAY && !value) {
        return cb('请输入支付宝账号');
      }
      cb();
    }
  }],
  wechatAccount: [{ 
    required: true, 
    message: '请输入微信账号',
    validator: (value: string, cb: (error?: string) => void) => {
      if (formData.paymentMethod === PaymentMethod.WECHAT && !value) {
        return cb('请输入微信账号');
      }
      cb();
    }
  }],
  paymentVoucher: [{ required: true, message: '请上传打款凭证' }],
};

// 监听记录变化，填充表单
watch(
  () => props.record,
  (val) => {
    if (val) {
      Object.assign(formData, { ...val });
    } else {
      Object.assign(formData, { ...defaultFormData });
    }
  },
  { immediate: true, deep: true }
);

// 监听可见性变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // 对话框打开时加载运营商列表
      loadPartnerOptions();
    }
  }
);

// 关闭对话框
function close() {
  emit('update:visible', false);
  // 重置表单
  formRef.value?.resetFields();
  Object.assign(formData, { ...defaultFormData });
}

// 加载运营商选项
async function loadPartnerOptions() {
  partnerLoading.value = true;
  try {
    const response = await axios.get('/api/partner/list');
    console.log('运营商列表响应数据:', response);
    
    // 实际接口返回格式是 {code: 200, message: '操作成功', data: Array(2)}
    // 使用类型断言处理实际返回数据
    const res = response as unknown as { code: number; message: string; data: PartnerOption[] };
    
    if (res.code === 200 && res.data) {
      partnerOptions.value = res.data;
      console.log('解析后的运营商选项:', partnerOptions.value);
    } else {
      partnerOptions.value = [];
      Message.warning('获取运营商列表为空');
    }
  } catch (error) {
    console.error('加载运营商列表失败:', error);
    Message.error('加载运营商列表失败');
    partnerOptions.value = [];
  } finally {
    partnerLoading.value = false;
  }
}

// 处理运营商选择变化
function handlePartnerChange(value: number) {
  const partner = partnerOptions.value.find(item => item.id === value);
  if (partner) {
    formData.partnerName = partner.partnerName || '';
  }
}

// 处理支付方式变化
function handlePaymentMethodChange() {
  // 清空相关字段
  formData.bankName = '';
  formData.bankAccount = '';
  formData.bankBranch = '';
  formData.alipayAccount = '';
  formData.wechatAccount = '';
}

// 计算实际到账金额
function calculateActualAmount() {
  if (formData.withdrawAmount !== undefined) {
    const feeRate = formData.feeRate || 0;
    const fee = formData.withdrawAmount * (feeRate / 100);
    formData.actualAmount = Number((formData.withdrawAmount - fee).toFixed(2));
  } else {
    formData.actualAmount = undefined;
  }
}

// 处理文件上传
async function handleUpload(options: any) {
  console.log('上传选项:', options);
  
  if (!options.fileItem?.file) {
    Message.error('请选择要上传的文件');
    return;
  }
  
  const file = options.fileItem.file;
  
  try {
    console.log('上传的文件对象:', file);
    console.log('文件类型:', file.type);
    console.log('文件大小:', file.size);
    console.log('文件名称:', file.name);
    
    const uploadFormData = new FormData();
    uploadFormData.append('file', file);
    
    // 检查 FormData 中的文件
    console.log('FormData 中的文件:', uploadFormData.get('file'));
    
    const response = await axios.post('/api/file/upload', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      transformRequest: [(data) => data], // 防止 axios 自动转换数据
    });
    
    console.log('上传响应:', response);
    
    if (response.code === 200) {
      formData.paymentVoucher = response.data.imgUrl;
      options.onSuccess(response);
      Message.success('上传成功');
    } else {
      options.onError(new Error(response.message || '上传失败'));
    }
  } catch (error: any) {
    console.error('上传文件失败:', error);
    console.error('错误详情:', error.response?.data);
    options.onError(error);
    Message.error(error.response?.message || '上传失败');
  }
}

// 上传前校验
function beforeUpload(file: File) {
  // 校验文件类型
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    Message.error('只能上传图片文件');
    return false;
  }
  
  // 校验文件大小（限制为5MB）
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    Message.error('图片大小不能超过5MB');
    return false;
  }
  
  return true;
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    if (props.isEdit && formData.id) {
      // 编辑
      await updatePartnerWithdraw(formData);
      Message.success('修改成功');
    } else {
      // 新增
      await createPartnerWithdraw(formData);
      Message.success('创建成功');
    }
    
    emit('success');
    close();
  } catch (error) {
    console.error('提交表单失败:', error);
    if (error instanceof Error) {
      Message.error(error.message);
    } else {
      Message.error('提交失败');
    }
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped>
.option-code {
  color: #8a8e99;
  margin-right: 8px;
  font-size: 13px;
}

.option-name {
  font-weight: 500;
}

.arco-select-option {
  display: flex;
  align-items: center;
}

.preview-image {
  margin-top: 8px;
  max-width: 200px;
  max-height: 200px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid var(--color-border);
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style> 